package org.jpass.dc.view.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UploadService {
	private static final Log log = LogFactory.getLog(MyMultiPartRequest.class);
	
	@SuppressWarnings("unchecked")  
    public static void upload(HttpServletRequest request,  
            HttpServletResponse response) throws IOException {  
		
        log.info("客户端提交类型: " + request.getContentType());  
        if (request.getContentType() == null) {  
            throw new IOException(  
                    "the request doesn't contain a multipart/form-data stream");  
        }  
          
        MyProgressListener p = new MyProgressListener(request) ; //定义监听器 
        // 上传临时路径  
        String path = request.getSession().getServletContext().getRealPath("/");  
        log.info("上传临时路径 : " + path);  
        // 设置上传工厂  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        factory.setRepository(new File(path));  
        // 阀值,超过这个值才会写到临时目录  
        factory.setSizeThreshold(1024 * 1024 * 10);  
        ServletFileUpload upload = new ServletFileUpload(factory);  
        // 最大上传限制  
        upload.setSizeMax(1024 * 1024 * 200);  
        // 设置监听器监听上传进度  
        upload.setProgressListener(p);  
        try {  
            log.info("解析上传文件....");  
            List<FileItem> items = upload.parseRequest(request);  
              
            log.info("上传数据...");  
            for (FileItem item : items) {  
                  
                // 非表单域  
                if (!item.isFormField()) {  
                    log.info("上传路径  : " + path + item.getName());  
                    FileOutputStream fos = new FileOutputStream(path + item.getName());  
                    // 文件全在内存中  
                    if (item.isInMemory()) {  
                        fos.write(item.get());  
                        p.setComplete(true);  
                    } else {  
                        InputStream is = item.getInputStream();  
                        byte[] buffer = new byte[1024];  
                        int len;  
                        while ((len = is.read(buffer)) > 0) {  
                            fos.write(buffer, 0, len);  
                        }  
                        is.close();  
                    }  
                    fos.close();  
                    log.info("完成上传文件!");  
                      
                    item.delete();  
                    log.info("删除临时文件!");  
                      
                    p.setComplete(true);  
                    log.info("更新progress对象状态为完成状态!");  
                }  
            }  
        } catch (Exception e) {  
            log.error("上传文件出现异常, 错误原因 : " + e.getMessage());  
            // 发生错误,进度信息对象设置为完成状态  
            p.setComplete(true);
        }  
    }
}
